package com.golddaymicromall.activity.jifenconfirmpay;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.activity.panicbuyingconfirmpay.PanicBuyingConfirmPayPwdActivity;
import com.golddaymicromall.activity.salemanager.ConfirmPayActivity;
import com.golddaymicromall.activity.setting.personal.address.AddressChoiceActivity;
import com.golddaymicromall.adapter.BonusPointsConfirmPayAdapter;
import com.golddaymicromall.adapter.PanicBuyingConfirmPayAdapter;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AddressInfo;
import com.golddaymicromall.bean.JiFenInfo;
import com.golddaymicromall.bean.PanicBuyingInfo;
import com.golddaymicromall.util.ActivityController;
import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

import static com.google.common.base.Preconditions.checkNotNull;

public class BonusPointsConfirmPayActivity extends BaseActivity implements BonusPointsConfirmPayContract.View {

    BonusPointsConfirmPayContract.Presenter mPresenter;
    @Bind(R.id.paincbuying_confirmpay_back)
    LinearLayout paincbuying_confirmpay_back;
    @Bind(R.id.paincbuying_confirmPay_changeAddress)
    LinearLayout paincbuying_confirmPay_changeAddress;
    @Bind(R.id.paincbuying_confirmPay_username)
    TextView paincbuying_confirmPay_username;
    @Bind(R.id.paincbuying_confirmPay_phone)
    TextView paincbuying_confirmPay_phone;
    @Bind(R.id.paincbuying_fragment_personal_llyt_relate)
    LinearLayout paincbuying_fragment_personal_llyt_relate;
    @Bind(R.id.paincbuying_confirmPay_address)
    TextView paincbuying_confirmPay_address;
    @Bind(R.id.paincbuying__listview)
    ListView paincbuying__listview;
    @Bind(R.id.paincbuying_num)
    TextView paincbuying_num;
    @Bind(R.id.allPrice)
    TextView mallPrice;
    @Bind(R.id.allPoint)
    TextView mallPoint;
    @Bind(R.id.orderdetial2PayPwd)
    LinearLayout orderdetial2PayPwd;
    @Bind(R.id.paincbuying_confirmpayment)
    TextView paincbuying_confirmpayment;

    private Observable<String> rxBusDataObservable;
    private String num;
    private String allPrice;
    private String allPv;
    private String allpoints;


    private List<JiFenInfo.DataBean> list;
    private List<JiFenInfo.DataBean> listFlag;
    private List<AddressInfo> listAddress = new ArrayList<AddressInfo>();
    private String addressid;
    public static final int REQUSET = 1;
    private BonusPointsConfirmPayAdapter adapter;
    private String mDeptFlag;
    private String customerId;
    private String ids;
    private String count;

    //接收返回的值
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConfirmPayActivity.REQUSET && resultCode == RESULT_OK) {
            addressid = data.getStringExtra("id");
            String nameAddress = data.getStringExtra("name_address");
            String address = data.getStringExtra("address");
            String phone = data.getStringExtra("phone");
            paincbuying_confirmPay_username.setText("收货人：" + nameAddress);
            paincbuying_confirmPay_phone.setText(phone);
            paincbuying_confirmPay_address.setText("地址：" + address);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bonuspoints_confirm_pay);
        ButterKnife.bind(this);
        customerId = SPUtils.get(getApplicationContext(), "Id", "").toString();
        mDeptFlag = SPUtils.get(getApplicationContext(), "deptFlag", "").toString();
        list = (List<JiFenInfo.DataBean>) getIntent().getSerializableExtra("listFlag");
        num = getIntent().getStringExtra("num");
        allPrice = getIntent().getStringExtra("allPrice");
        allpoints = getIntent().getStringExtra("allpoints");
        allPv = getIntent().getStringExtra("allPv");
        ids = getIntent().getStringExtra("ids");
        Log.e("ids", ids);
        count = getIntent().getStringExtra("count");
        Log.e("count", count);
        initView();

    }

    private void initView() {
        String customerid = SPUtils.get(this, "Id", "").toString();
        //初始化
        new BonusPointsConfirmPayPresenter(this);
        //加载数据
        mPresenter.getPanicBuyingAdressConfirmPayInfo(customerid);
//        for (int i = 0; i < list.size(); i++) {
//            if (list.get(i).getCount() == 0) {
//                list.remove(i);
//            }
//        }
        adapter = new BonusPointsConfirmPayAdapter(list, BonusPointsConfirmPayActivity.this);
        paincbuying__listview.setAdapter(adapter);
        paincbuying_num.setText("共 " + num + " 种商品");
        mallPrice.setText(allPrice);
        mallPoint.setText(allpoints);
    }


    @Override
    public void showPanicBuyingAdressConfirmPayInfo(String productInfo) {

        if (!"".equals(productInfo)) {
            if (productInfo.contains("errorToken") || "0".equals(productInfo)) {
                Toast.makeText(BonusPointsConfirmPayActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
            } else if ("null".equals(productInfo)) {
//                            Toast.makeText(ConfirmPayActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                paincbuying_confirmPay_address.setText("您还没有收货地址，请到个人设置中设置");
            } else {
                listAddress = JSON.parseArray(productInfo, AddressInfo.class);
                for (int i = 0; i < listAddress.size(); i++) {
                    if ("1".equals(listAddress.get(i).getAddress_default())) {
                        addressid = listAddress.get(i).getId();
                        paincbuying_confirmPay_username.setText("收货人：" + listAddress.get(i).getReceivername());
                        paincbuying_confirmPay_phone.setText(listAddress.get(i).getPhone());
                        paincbuying_confirmPay_address.setText("地址：" + listAddress.get(i).getCountryname() + listAddress.get(i).getProvincename()
                                + listAddress.get(i).getCityname() + listAddress.get(i).getAreaname() + listAddress.get(i).getStreet());
                    }
                }
            }


        }

    }

    @Override
    public void showPanicBuyingConfirmPayCreateOrderInfo(String productInfo) {
        if ("0".equals(productInfo)) {
            Toast.makeText(BonusPointsConfirmPayActivity.this, "确认结算失败，请重新提交", Toast.LENGTH_SHORT).show();
        } else if ("2".equals(productInfo)) {
            Toast.makeText(BonusPointsConfirmPayActivity.this, "数量不足", Toast.LENGTH_SHORT).show();
        } else if ("3".equals(productInfo)) {
            Toast.makeText(BonusPointsConfirmPayActivity.this, "抢没了", Toast.LENGTH_SHORT).show();
        } else {
            dialog(productInfo);
        }
    }

    protected void dialog(String productInfo) {

        AlertDialog.Builder builder = new AlertDialog.Builder(BonusPointsConfirmPayActivity.this);

        builder.setMessage("确认退出吗?");
        builder.setCancelable(false);
        builder.setTitle("提示");
        builder.setMessage("订单已提交到销售管理页面！\n点击“确定”继续支付，\n点击“取消”返回继续购买");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置你的操作事项
                Intent intent2PayPwd = new Intent(BonusPointsConfirmPayActivity.this, BonusPointsConfirmPayPwdActivity.class);
                intent2PayPwd.putExtra("orderId", productInfo);
                startActivity(intent2PayPwd);
                MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(),
                        SPUtils.get(getApplicationContext(), "Customerno", "").toString() + "抢购订单编号：" + productInfo + ",价格：" + allPrice);
                finish();


            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置你的操作事项
                finish();
            }
        });
        builder.create().show();
    }


    @OnClick({R.id.paincbuying_confirmPay_changeAddress, R.id.paincbuying_confirmpayment, R.id.paincbuying_confirmpay_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.paincbuying_confirmpay_back:
                ActivityController.getInstance().removeActivity(this);
                finish();
                break;
            case R.id.paincbuying_confirmPay_changeAddress:
                Intent intent2choiceaddress = new Intent(this, AddressChoiceActivity.class);
                startActivityForResult(intent2choiceaddress, REQUSET);
                break;
            case R.id.paincbuying_confirmpayment:
                attemptCreateOrder("");
                break;
        }
    }

    private void attemptCreateOrder(String flag) {

        if (list.size() == 0) {
            Toast.makeText(this, "请选择购买的物品,谢谢", Toast.LENGTH_SHORT).show();
            return;
        } else if (paincbuying_confirmPay_address.getText().toString().contains("没有")) {
            Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
            return;
        } else {
            //加载数据
            mPresenter.getPanicBuyingConfirmPayCreateOrderInfo(ids, count, addressid, customerId, allPrice, allPv, allpoints, "1");
        }

    }


    /**
     * if (!"0".equals(materialBringBackInfo.getRecords()) && !"[]".equals(materialBringBackInfo.getRows().toString())) {
     * infos.addAll(materialBringBackInfo.getRows());
     * adapter.notifyDataSetChanged();
     * } else {
     * SnackbarManager.show(Snackbar.with(MaterialBringBackActivity.this).text("没有更多数据了").duration(1000));
     * }
     * <p>
     * if (materialTypeInfo.isSuccess() && "1".equals(materialTypeInfo.getCode())) {
     */

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void dismissLoading() {
        super.dismissLoading();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.unsubscribe();
    }

    @Override
    public void setPresenter(BonusPointsConfirmPayContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }
}
